import axios from 'axios';
import type {AxiosResponse, AxiosError, AxiosInstance, AxiosRequestConfig} from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import {REFRESH_TOKEN_CODE} from '@/config';
import {
	localStg,
	handleAxiosError,
	handleBackendError,
	handleResponseError,
	handleServiceResult,
	transformRequestData, sessionStg
} from '@/utils';
import { refreshTokenHandler} from './helpers';

type RefreshRequestQueue = (config: AxiosRequestConfig) => void;

/**
 * 封装axios请求类
 * @author Soybean<honghuangdc@gmail.com>
 */
export default class CustomAxiosInstance {
	instance: AxiosInstance;

	backendConfig: Service.BackendResultConfig;

	isRefreshing: boolean;

	retryQueues: RefreshRequestQueue[];


	/**
	 *
	 * @param axiosConfig - axios配置
	 * @param backendConfig - 后端返回的数据配置
	 */
	constructor(
		axiosConfig: AxiosRequestConfig,
		backendConfig: Service.BackendResultConfig = {
			codeKey: 'code',
			dataKey: 'data',
			msgKey: 'message',
			successCode: 200
		}
	) {
		this.backendConfig = backendConfig;
		this.instance = axios.create(axiosConfig);
		this.setInterceptor();
		this.isRefreshing = false;
		this.retryQueues = [];
	}


	/** 设置请求拦截器 */

	setInterceptor() {
		this.instance.interceptors.request.use(
			async config => {
				const token = localStg.get("token");
				if (token && !config.headers?.skipToken){
					config.headers!["Authorization"] = `Bearer ${token}`;
				}
				return config;
			},
			(axiosError: AxiosError) => {
				const error = handleAxiosError(axiosError);
				return handleServiceResult(error, null);
			}
		);
		this.instance.interceptors.response.use(
			(async response => {
				if(response.data.code!=200){
					const error = handleBackendError(response.data, this.backendConfig);
					return handleServiceResult(error,null)
				}
				return response.data;
			}) as (response: AxiosResponse<any, any>) => Promise<AxiosResponse<any, any>>,
			(axiosError: AxiosError) => {
				const status = Number(axiosError.response.status) || 200;
				if (status === 424) {
					ElMessageBox.confirm('令牌状态已过期，请点击重新登录','系统提示',{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					}).then(()=>{
							localStg.clear();
							sessionStg.clear();
							window.location.href = '/';
							return;
						})
				}
				return Promise.reject(axiosError.response.data);
			}
		);
	// setInterceptor() {
	// 	this.instance.interceptors.request.use(
	// 		async config => {
	// 			const handleConfig = {...config};
	// 			console.log(localStg.get("token"));
	// 			if (localStg.get("token")) {
	// 				let currentTime = new Date().getTime();
	// 				let tokenExpire = localStg.get("tokenExpire");
	// 				// 大于token时间
	// 				if (currentTime > tokenExpire && !this.isRefreshing) {
	// 					this.isRefreshing = true;
	// 					// 刷新token
	// 					const {data} = await refreshTokenHandler();
	// 					console.log("data", data)
	// 					this.isRefreshing = false;
	// 				}
	// 			}
	//
	// 			if (handleConfig.headers) {
	// 				// 数据转换
	// 				const contentType = handleConfig.headers['Content-Type'] as UnionKey.ContentType;
	// 				handleConfig.data = await transformRequestData(handleConfig.data, contentType);
	// 				// 不设置认证头uri
	// 				if (handleConfig.url.indexOf('/system/tenant/selectList') > -1) {
	// 					console.log("aa")
	// 				} else {
	// 					// 设置token
	// 					if (!handleConfig.headers['Authorization']) {
	// 						handleConfig.headers.Authorization = "Bearer " + localStg.get('token') || '';
	// 					}
	// 				}
	//
	//
	// 			}
	// 			return handleConfig;
	// 		},
	// 		(axiosError: AxiosError) => {
	// 			const error = handleAxiosError(axiosError);
	// 			return handleServiceResult(error, null);
	// 		}
	// 	);
	// 	this.instance.interceptors.response.use(
	// 		(async response => {
	// 			const {status, config} = response;
	// 			if (status === 200 || status < 300 || status === 304) {
	// 				const backend = response.data;
	// 				const {codeKey, dataKey, successCode} = this.backendConfig;
	// 				// 请求成功
	// 				if (backend[codeKey] === successCode) {
	// 					return handleServiceResult(null, backend[dataKey]);
	// 				}
	// 				// // token失效, 刷新token
	// 				// if (REFRESH_TOKEN_CODE.includes(backend[codeKey])) {
	// 				//   // 原始请求
	// 				//   const originRequest = new Promise(resolve => {
	// 				//     this.retryQueues.push((refreshConfig: AxiosRequestConfig) => {
	// 				//       config.headers.Authorization = refreshConfig.headers?.Authorization;
	// 				//       resolve(this.instance.request(config));
	// 				//     });
	// 				//   });
	// 				//   if (!this.isRefreshing) {
	// 				//     this.isRefreshing = true;
	// 				//     const refreshConfig = await handleRefreshToken(response.config);
	// 				// 		debugger
	// 				//     if (refreshConfig) {
	// 				//       this.retryQueues.map(cb => cb(refreshConfig));
	// 				//     }
	// 				//     this.retryQueues = [];
	// 				//     this.isRefreshing = false;
	// 				//   }
	// 				//   return originRequest;
	// 				// }
	//
	// 				const error = handleBackendError(backend, this.backendConfig);
	// 				return handleServiceResult(error, null);
	// 			}
	// 			const error = handleResponseError(response);
	// 			return handleServiceResult(error, null);
	// 		}) as (response: AxiosResponse<any, any>) => Promise<AxiosResponse<any, any>>,
	// 		(axiosError: AxiosError) => {
	// 			const error = handleAxiosError(axiosError);
	// 			return handleServiceResult(error, null);
	// 		}
	// 	);
	}
}
